package com.java.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.product.dao.ProductAttrValueDao;
import com.java.shop.product.entity.AttrEntity;
import com.java.shop.product.entity.ProductAttrValueEntity;
import com.java.shop.product.service.AttrService;
import com.java.shop.product.service.ProductAttrValueService;
import com.java.shop.product.vo.Attr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveProductAttrValue(Long spuId, List<Attr> baseAttrs) {
        if(baseAttrs != null && baseAttrs.size() > 0){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
                ProductAttrValueEntity attrValue = new ProductAttrValueEntity();
                attrValue.setAttrId(item.getAttrId());
                AttrEntity attrEntity = attrService.getById(item.getAttrId());
                attrValue.setAttrName(attrEntity.getAttrName());
                attrValue.setAttrValue(item.getAttrValues());
                attrValue.setSpuId(spuId);
                return attrValue;
            }).collect(Collectors.toList());

            this.saveBatch(collect);
        }
    }

    /**
     * 根据spuid 获取基本属性的值
     * @param spuId
     * @return
     */
    @Override
    public List<ProductAttrValueEntity> baseAttrForSpu(Long spuId) {
        return this.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }
}